package com.gzhryc.shared_device.oem.h5.agent.controllers.api.v1.place;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.api.DefaultAPIResponse;
import com.gzhryc.common.data.ValidateTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlaceFreeMember;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlacePhysicalStore;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlaceProfitUser;
import com.gzhryc.shared_device.oem.code.place.services.PlaceFreeMemberService;
import com.gzhryc.shared_device.oem.code.place.services.PlacePhysicalStoreService;
import com.gzhryc.shared_device.oem.code.place.services.PlaceProfitUserService;
import com.gzhryc.shared_device.oem.code.place.services.dto.PlaceFreeMemberSearch;
import com.gzhryc.shared_device.oem.code.user.ERoleType;
import com.gzhryc.shared_device.oem.h5.agent.ClientAPICodeConstants;
import com.gzhryc.shared_device.oem.h5.agent.LoginUser;
import com.gzhryc.shared_device.oem.h5.agent.WebConstants;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.place.PlaceFreeMemberDelRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.place.PlaceFreeMemberListRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.place.PlaceFreeMemberListResponse;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.place.PlaceFreeMemberSaveRequest;

public class PlaceFreeMemberController {
	
	@Route(value = "/agent/api/v1/free_member/list.data")
    public PlaceFreeMemberListResponse freeMemberList(HttpServletRequest request){
		PlaceFreeMemberListResponse apiResp = new PlaceFreeMemberListResponse(ClientAPICodeConstants.NULL_DATA,"暂无数据");
		PlaceFreeMemberListRequest apiReq = WebUtils.getJsonRequest(request,PlaceFreeMemberListRequest.class);
        if(apiReq != null) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null){
            	Long userId = loginUser.getId();
            	if(!ERoleType.Agent.index().equals(loginUser.getRoleType())) {
            		if(ERoleType.Partner.index().equals(loginUser.getRoleType())) {
            			userId = loginUser.getParentId();
            		}else {
            			apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"无权限操作");
            			return apiResp;
            		}
            	}
            	
                PlaceFreeMemberSearch search = new PlaceFreeMemberSearch();
                search.setPlaceUserId(userId);
                search.setPhone(apiReq.getBody().getTrim());
                List<PlaceFreeMember> freeMemberList = PlaceFreeMemberService.self().findJoinBySearch(search,apiReq.getBody().getPageNo()
                		,WebConstants.PAGE_LIMIT);
                if(freeMemberList != null && freeMemberList.size() > 0) {
                	apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                	apiResp.getBody().setItems(new ArrayList<>());
                	for(PlaceFreeMember freeMember : freeMemberList) {
                		PlaceFreeMemberListResponse.Item item = new PlaceFreeMemberListResponse.Item();
                		item.setPlaceId(freeMember.getPlaceId());
                		item.setPlaceName(freeMember.getPlace().getName());
                		item.setPhone(freeMember.getPhone());
                		item.setMemberId(freeMember.getMemberId());
                		item.setMemberNickname(freeMember.getMemberNickname());
                		item.setNote(freeMember.getNote());
                		item.setActiveDate(freeMember.getActiveDate());
                		item.setCreateDate(freeMember.getCreateDate());
                		apiResp.getBody().getItems().add(item);
                	}
                }
            }
        }
        return apiResp;
	}

	@Route(value = "/agent/api/v1/place/free_member/list.data")
    public PlaceFreeMemberListResponse placeFreeMemberList(HttpServletRequest request){
		PlaceFreeMemberListResponse apiResp = new PlaceFreeMemberListResponse(ClientAPICodeConstants.NULL_DATA,"暂无数据");
		PlaceFreeMemberListRequest apiReq = WebUtils.getJsonRequest(request,PlaceFreeMemberListRequest.class);
        if(apiReq != null && apiReq.getBody().getPlaceId() != null) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null){
            	PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(apiReq.getBody().getPlaceId());
                if (physicalStore == null) {
                    apiResp.setCode(ClientAPICodeConstants.EXECUTE_ERROR,"未找到网点");
                    return apiResp;
                }

                PlaceProfitUser profitUser = null;

                if(ERoleType.Agent.index().equals(loginUser.getRoleType())) {
                    if (!physicalStore.getUserId().equals(loginUser.getId())) {
                        apiResp.setCode(ClientAPICodeConstants.NOT_POWER, "无权限查看");
                        return apiResp;
                    }
                }else {
                    profitUser = PlaceProfitUserService.self().getJoinByKeys(physicalStore.getId(),loginUser.getId());
                    if(profitUser == null){
                        apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"无权限查看");
                        return apiResp;
                    }
                    if(!loginUser.getParentId().equals(profitUser.getPlaceUserId())){
                        apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"无权限查看");
                        return apiResp;
                    }
                }
                PlaceFreeMemberSearch search = new PlaceFreeMemberSearch();
                search.setPlaceId(physicalStore.getId());
                search.setPhone(apiReq.getBody().getTrim());
                List<PlaceFreeMember> freeMemberList = PlaceFreeMemberService.self().findJoinBySearch(search);
                if(freeMemberList != null && freeMemberList.size() > 0) {
                	apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                	apiResp.getBody().setItems(new ArrayList<>());
                	for(PlaceFreeMember freeMember : freeMemberList) {
                		PlaceFreeMemberListResponse.Item item = new PlaceFreeMemberListResponse.Item();
                		item.setPhone(freeMember.getPhone());
                		item.setMemberId(freeMember.getMemberId());
                		item.setMemberNickname(freeMember.getMemberNickname());
                		item.setNote(freeMember.getNote());
                		item.setActiveDate(freeMember.getActiveDate());
                		item.setCreateDate(freeMember.getCreateDate());
                		apiResp.getBody().getItems().add(item);
                	}
                }
            }
        }
        return apiResp;
	}
	
	@Route(value = "/agent/api/v1/place/free_member/save.do")
    public DefaultAPIResponse doSave(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR, "保存白名单失败");
        PlaceFreeMemberSaveRequest apiReq = WebUtils.getJsonRequest(request, PlaceFreeMemberSaveRequest.class);
        if (apiReq != null && apiReq.getBody().getPlaceId() != null && StringTools.isNotBlank(apiReq.getBody().getPhone())) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null) {
                if (!ValidateTools.isPhone(apiReq.getBody().getPhone())) {
                    apiResp.setMsg("手机号不正确，请检查");
                    return apiResp;
                }
                
                Long userId = loginUser.getId();
            	if(!ERoleType.Agent.index().equals(loginUser.getRoleType())) {
            		if(ERoleType.Partner.index().equals(loginUser.getRoleType())) {
            			userId = loginUser.getParentId();
            		}else {
            			apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"无权限操作");
            			return apiResp;
            		}
            	}

                PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(apiReq.getBody().getPlaceId());
                if(physicalStore == null){
                    apiResp.setMsg("未找到网点信息");
                    return apiResp;
                }

                if(!physicalStore.getUserId().equals(userId)){
                    apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"无权限操作");
                    return apiResp;
                }
                
                PlaceFreeMember freeMember = PlaceFreeMemberService.self().getByKeys(physicalStore.getId(), apiReq.getBody().getPhone());
                if(freeMember != null) {
                	freeMember.setNote(apiReq.getBody().getNote());
                	if(PlaceFreeMemberService.self().updateNotNull(freeMember)) {
                		apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                	}
                }else {
                	freeMember = new PlaceFreeMember();
                	freeMember.setPlaceId(physicalStore.getId());
                	freeMember.setPhone(apiReq.getBody().getPhone());
                	freeMember.setNote(apiReq.getBody().getNote());
                	freeMember.setPlace(physicalStore);
                	try {
						if(PlaceFreeMemberService.self().add(freeMember)) {
							apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
						}
					} catch (LogicException e) {
						apiResp.setMsg(e.getMessage());
					}
                }
            }
        }
        return apiResp;
    }
	
	@Route(value = "/agent/api/v1/place/free_member/del.do")
    public DefaultAPIResponse doDel(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR, "删除白名单失败");
        PlaceFreeMemberDelRequest apiReq = WebUtils.getJsonRequest(request, PlaceFreeMemberDelRequest.class);
        if (apiReq != null && apiReq.getBody().getPlaceId() != null && StringTools.isNotBlank(apiReq.getBody().getPhone())) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null ) {
            	Long userId = loginUser.getId();
            	if(!ERoleType.Agent.index().equals(loginUser.getRoleType())) {
            		if(ERoleType.Partner.index().equals(loginUser.getRoleType())) {
            			userId = loginUser.getParentId();
            		}else {
            			apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"无权限操作");
            			return apiResp;
            		}
            	}

                PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(apiReq.getBody().getPlaceId());
                if(physicalStore == null){
                    apiResp.setMsg("未找到网点信息");
                    return apiResp;
                }

                if(!physicalStore.getUserId().equals(userId)){
                    apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"无权限操作");
                    return apiResp;
                }
                
                try {
                    if (PlaceFreeMemberService.self().deleteByKeys(apiReq.getBody().getPlaceId(),apiReq.getBody().getPhone())) {
                        apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                    }
                } catch (LogicException e) {
                    apiResp.setMsg(e.getMessage());
                }
            }
        }
        return apiResp;
    }
 
}
